package main

import (
	"io"
	"log"
	"net/http"
)

type Proxy struct {
}

func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	log.Printf("Received request: %s %s %s:\n", r.Method, r.Host, r.RemoteAddr)
	// 1.代理服务器接收客户端请求，复制然后封装成新的请求
	forwardReq := &http.Request{}
	*forwardReq = *r

	// 2.发送新的请求到下游真实服务器，接收响应
	transport := http.DefaultTransport
	res, err := transport.RoundTrip(forwardReq)
	defer res.Body.Close()
	if err != nil {
		w.WriteHeader(http.StatusBadGateway)
		return
	}

	// 3.处理响应并返回上游客户端
	for key, values := range res.Header {
		for _, value := range values {
			w.Header().Add(key, value)
		}
	}

	w.WriteHeader(res.StatusCode)
	io.Copy(w, res.Body)
}

// 正向代理
func main() {
	log.Println("正向代理服务器启动: localhost:8000")
	http.Handle("/", &Proxy{})
	http.ListenAndServe(":8000", nil)
}
